﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace Agents.Admin
{
    //page uplouds all of the agents details 
    //page allows the administrater to edit and change the agents details
    public partial class EditAgent : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            //only spill the existing agents information if we just entered the page
            //(and not if the page was loaded because of a page event)
            if (Page.IsPostBack == false)
            {
                int agentId = Convert.ToInt32(Request.QueryString["agentId"]);
                Queries queries = new Queries();
                Agents agent = queries.GetAgent(agentId);
                
                //spilling all existing agent information onto page
                nameTxtbox.Text = agent.Name;
                phoneTxtbox.Text = agent.Phone;
                emailTxtbox.Text = agent.EMail;

                // Bind the regions list
                cmbArea.DataSource = queries.GetAllRegions();
                cmbArea.DataValueField = "Id";
                cmbArea.DataTextField = "Name";

                // Choose the selected region after binding
                cmbArea.DataBound += new EventHandler(
                    (s, ev) => { cmbArea.Items.FindByValue(agent.Region.ToString()).Selected = true; });

                cmbArea.DataBind();

                idTxtbox.Text = agent.TZ;
                usernameTxtbox.Text = agent.UserName;
            }
        }

        protected void okBtn_Click(object sender, EventArgs e)
        {
            Queries q = new Queries();

            //making sure all text boxes have been filled
            if (nameTxtbox.Text == "" || phoneTxtbox.Text == "" || emailTxtbox.Text == ""
                || cmbArea.SelectedItem == null || idTxtbox.Text == "")
                //if something is missing- print apropriot message to screan.
                empty.Text = ".קיימים שדות ריקים. אנא, מלא את כולם";

            else
            {
                int agentId = Convert.ToInt32(Request.QueryString["agentId"]);

                //making sure the new agent name does not exist in our data base for another agent.
                if (q.CheckClientNameColision(agentId, nameTxtbox.Text))
                {
                    // Disable the buttons so the user can't interfere
                    backBtn.Enabled = false;
                    okBtn.Enabled = false;

                    // Editing the agent
                    q.EditAgent(agentId, nameTxtbox.Text, phoneTxtbox.Text, idTxtbox.Text,
                                emailTxtbox.Text, Int32.Parse(cmbArea.SelectedValue));

                    // Announce success and wait for 2 seconds before redirecting
                    empty.Text = "הסוכן עודכן בהצלחה";
                    redirectionTimer.Enabled = true;
                }
                //if the client already exists- print apropriate message to screan
                else 
                {
                    empty.Text = "שם הסוכן כבר נמצא במערכת";
                }
            }
        }

        //function for redirectiong the administrater back to his homepage.
        protected void backBtn_Click(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }

        /// <summary>
        /// Occurs when the Reset Password button is clicked and 
        /// resets the user's password
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnResetPassword_Click(object sender, EventArgs e)
        {
            Queries queries = new Queries();

            // Get the agent
            int agentId = Convert.ToInt32(Request.QueryString["agentId"]);
            Agents agent = queries.GetAgent(agentId);

            // Reset the password
            String newPassword = queries.ResetPassword(agent.UserName);

            lblNewPassword.Text = "הסיסמה התאפסה בהצלחה. הסיסמה החדשה היא: " +
                newPassword;
        }

        /// <summary>
        /// Redirect back to the admin menu after a few seconds
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void redirectionTimer_Tick(object sender, EventArgs e)
        {
            Response.Redirect("~/Admin/AdminMenu.aspx");
        }
    }
}